'''
Created on Sep 18, 2012

@author: thomas_dao
'''
from web import base
from web.base import BaseHandler
from web import urls
from kid import util
import json
import logging
from google.appengine.ext import ndb
from entity.entity import Comment, FollowUser
from app import article_async, comment_async
from webapp2_extras.appengine.auth.models import User

class CreateHandler(BaseHandler):
    @ndb.synctasklet
    @base.user_required
    def post(self):
        # Get input data
        content = self.request.params.get('content')
        url = self.request.params.get('url')
        
        # Create new entity
        comment = Comment()
        comment.content = content
        comment.url = url
        comment.user = util.get_current_user_key()
        comment.put()
        
        comment_dict = yield util.ndb_to_dict_async(comment, detail=["user"])
        
        self.response.write(json.dumps(comment_dict))

class ReadHandler(BaseHandler):
    def get(self):
        pass    

class UpdateHandler(BaseHandler):
    @ndb.synctasklet
    @base.user_required
    def post(self):
        username = self.request.params.get('username')
        about_me = self.request.params.get('about_me')
        user = util.get_current_user_key().get()
        
        # Update
        user.username = username
        user.about_me = about_me
        user.put()
        
        self.response.write(json.dumps(util.ndb_to_dict(user)))
    

class DeleteHandler(BaseHandler):
    def post(self):
        pass


class FollowUserHandler(BaseHandler):
    def post(self):
        followee_id = self.request.params.get('followee_id')
        followee_key = ndb.Key(User, int(followee_id))
        follower_key = util.get_current_user_key()
        
        qry = FollowUser.query(FollowUser.follower==follower_key, 
                               FollowUser.followee==followee_key)
        follow = qry.get()
        if not follow:
            follow = FollowUser()
            follow.follower = follower_key
            follow.followee = followee_key
            follow.state = True
        else:
            follow.state = not follow.state
        
        follow.put()
        
        self.response.write(json.dumps(util.ndb_to_dict(follow)))
        

app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()